package net.uofitorn.bigtwo;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;

public class TableView extends SurfaceView implements SurfaceHolder.Callback {	
	
    private TableThread thread;
    private Context context;
    
	public TableView (Context context) {
        super(context);
        this.context = context;
        // register our interest in hearing about changes to our surface
        SurfaceHolder holder = getHolder();
        holder.addCallback(this);

        // create thread only; it's started in surfaceCreated()
/*        thread = new TableThread(holder, context, new Handler() {
            @Override
            public void handleMessage(Message m) {

            }
        });*/

        setFocusable(true); // make sure we get key events
	}
  
	@Override
	protected void onDraw(Canvas canvas) {
		try {  
			Thread.sleep(30);  
		} catch (InterruptedException e) { }
		invalidate();  // Force a re-draw
	}
   
	// Called back when the view is first created or its size changes.
	@Override
	public void onSizeChanged(int w, int h, int oldW, int oldH) {

	}
	
    /* Callback invoked when the surface dimensions change. */
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        thread.setSurfaceSize(width, height);
    }
    
    /*
     * Callback invoked when the Surface has been created and is ready to be
     * used.
     */
    public void surfaceCreated(SurfaceHolder holder) {
    	if(thread == null){
    		thread = new TableThread(holder, context, new Handler() {
                @Override
                public void handleMessage(Message m) {

                }
            });
            // start the thread here so that we don't busy-wait in run()
            // waiting for the surface to be created
            thread.setRunning(true);
            thread.start();
    		return;
    	}
    		
    	if(thread.getState() == Thread.State.TERMINATED){
            thread = new TableThread(holder, context, new Handler() {
                @Override
                public void handleMessage(Message m) {

                }
            });
            // start the thread here so that we don't busy-wait in run()
            // waiting for the surface to be created
            thread.setRunning(true);
            thread.start();
    	}
    }

    /*
     * Callback invoked when the Surface has been destroyed and must no longer
     * be touched. WARNING: after this method returns, the Surface/Canvas must
     * never be touched again!
     */
    public void surfaceDestroyed(SurfaceHolder holder) {
        // we have to tell thread to shut down & wait for it to finish, or else
        // it might touch the Surface after we return and explode
        boolean retry = true;
        thread.setRunning(false);
        while (retry) {
            try {
                thread.join();
                retry = false;
            } catch (InterruptedException e) {
            }
        }
    }
    
    public TableThread getThread() {
        return thread;
    }
    
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return thread.doTouchEvent(event);
    }
	
    class TableThread extends Thread {

        private boolean mRun = false;

        /** The drawable to use as the background of the animation canvas */
        private Bitmap cards;
        private Bitmap card;
        private Bitmap backgroundImage;
        
        private Drawable mLanderImage;
        private int mLanderHeight;
        private int mLanderWidth;

        private Handler mHandler;
        private Context mContext;
        
        private int mCanvasHeight = 1;
        private int mCanvasWidth = 1;
        
        private int landerX = 50;
        private int landerY = 50;

        private SurfaceHolder mSurfaceHolder;

        public TableThread(SurfaceHolder surfaceHolder, Context context, Handler handler) {
            Resources res = context.getResources();
            mSurfaceHolder = surfaceHolder;
            mHandler = handler;
            mContext = context;
            mLanderImage = context.getResources().getDrawable(R.drawable.lander_plain);
            backgroundImage = BitmapFactory.decodeResource(res, R.drawable.tablewooden);
            cards = BitmapFactory.decodeResource(res, R.drawable.cards);
            card  = Bitmap.createBitmap(cards, 0, 0, 79, 123);
            mLanderWidth = mLanderImage.getIntrinsicWidth();
            mLanderHeight = mLanderImage.getIntrinsicHeight();
        }
        
        boolean doTouchEvent(MotionEvent event) {
        	switch(event.getAction()) {
        		case MotionEvent.ACTION_DOWN:
        		case MotionEvent.ACTION_MOVE:
        			landerX = (int) event.getX();
        			landerY = (int) event.getY();
        	}
        	return true;
        }

        /**
         * Starts the game, setting parameters for the current difficulty.
         */
        public void doStart() {
            synchronized (mSurfaceHolder) {
            	List<Card> cards = new ArrayList<Card>();
            }
        }

        @Override
        public void run() {
            while (mRun) {
                Canvas c = null;
                try {
                    c = mSurfaceHolder.lockCanvas(null);
                    synchronized (mSurfaceHolder) {
                        //if (mMode == STATE_RUNNING) updatePhysics();
                        doDraw(c);
                    }
                } finally {
                    // do this in a finally so that if an exception is thrown
                    // during the above, we don't leave the Surface in an
                    // inconsistent state
                    if (c != null) {
                        mSurfaceHolder.unlockCanvasAndPost(c);
                    }
                }
            }
        }
        
        public void setRunning(boolean b) {
            mRun = b;
        }

        /**
         * Draws the ship, fuel/speed bars, and background to the provided
         * Canvas.
         */
        private void doDraw(Canvas canvas) {
        	canvas.drawBitmap(backgroundImage, 0, 0, null);
            mLanderImage.setBounds(landerX - mLanderWidth, landerY - mLanderHeight, landerX, landerY);
            mLanderImage.draw(canvas);
            canvas.drawBitmap(card, 0, 0, null);
        }
        
        /* Callback invoked when the surface dimensions change. */
        public void setSurfaceSize(int width, int height) {
        	Log.w("TableView", "setSurfaceSize being called");
            synchronized (mSurfaceHolder) {
                mCanvasWidth = width;
                mCanvasHeight = height;
                // don't forget to resize the background image
                backgroundImage = Bitmap.createScaledBitmap(backgroundImage, width, height, true);
            }
        }
    }
}
